package com.tom.demo.service.system.impl;
import com.github.pagehelper.PageInfo;
import com.tom.demo.common.esEntity.SysLogDocIndex;
import com.tom.demo.common.response.Result;
import com.tom.demo.esRepository.SysLogRepository;
import com.tom.demo.service.system.LogService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;

@Slf4j
@Service
public class LogServiceImpl implements LogService {

    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Resource
    private RestHighLevelClient restHighLevelClient;

    @Resource
    private SysLogRepository sysLogRepository;


    @Override
    public Result pageList(Integer page, Integer pageSize,SysLogDocIndex sysLogDocIndex) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if(StringUtils.hasText(sysLogDocIndex.getRequestMethod())){
            //filter 根据请求方法过滤 逻辑“与”AND 只用于过滤。
            boolQueryBuilder.filter(QueryBuilders.matchQuery("requestMethod",sysLogDocIndex.getRequestMethod()));
        }
        if(StringUtils.hasText(sysLogDocIndex.getOperaCode())){
            boolQueryBuilder.filter(QueryBuilders.matchQuery("operaCode",sysLogDocIndex.getOperaCode()));
        }
        MultiMatchQueryBuilder multiMatchQueryBuilder = null;
        if(StringUtils.hasText(sysLogDocIndex.getKeyWord())){
            multiMatchQueryBuilder = QueryBuilders.multiMatchQuery(sysLogDocIndex.getKeyWord(),
                    "operaModel",
                    "operaDesc",
                    "requestUrl",
                    "requestIp",
                    "operaNickName");
        }
        assert multiMatchQueryBuilder != null;
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withPageable(PageRequest.of(page - 1, pageSize))
                //过滤条件
                .withFilter(boolQueryBuilder)
                .withQuery(multiMatchQueryBuilder)
                .withSort(SortBuilders.fieldSort("_score").order(SortOrder.DESC))
                .withSort(SortBuilders.fieldSort("operaDateTime").order(SortOrder.ASC))
                .withSort(SortBuilders.fieldSort("operaCostTime").order(SortOrder.ASC))
                .build();
        SearchHits<SysLogDocIndex> searchHits = elasticsearchRestTemplate.search(
                searchQuery,
                SysLogDocIndex.class,
                IndexCoordinates.of("sys_logs"));

        PageInfo<SysLogDocIndex> pageInfo = new PageInfo<>();
        pageInfo.setTotal(searchHits.getTotalHits());//总条数
        List<SysLogDocIndex> dataList = new LinkedList<>();
        searchHits.forEach(searchHit-> {
            dataList.add(searchHit.getContent());
        });
        pageInfo.setList(dataList);//当前页的数据
        pageInfo.setPageNum(page);//当前页码
        pageInfo.setSize(pageSize);//每页多少条数据
        long value = searchHits.getTotalHits();
        int intValue = new Double(value).intValue();
        //总共多少页
        int pages = intValue / pageSize;
        pageInfo.setPages(pages);
        return Result.success(pageInfo);
    }

    @Override
    public Result deleteById(String id) {
        sysLogRepository.deleteById(id);
        return Result.success();
    }
}
